package com.security.config.filter;

import com.alibaba.fastjson.JSON;
import com.security.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.web.session.InvalidSessionStrategy;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 当 session 失效后的处理
 */
@Slf4j
@Component("costomInvalidSessionStrategy")
public class CostomInvalidSessionStrategy implements InvalidSessionStrategy {

    @Override
    public void onInvalidSessionDetected
            (HttpServletRequest req, HttpServletResponse res)
            throws IOException, ServletException {
        cancelCookie(req,res);
        log.info("-----------认证已过期-----------");
        if(StringUtils.isNotEmpty(req.getHeader("X-Requested-With")) && "XMLHttpRequest".equals(req.getHeader("X-Requested-With").toString())){
            log.info("-----------AJAX SESSION 过期处理-----------");
            res.setContentType("application/json;charset=UTF-8");
            res.getWriter().write(JSON.toJSONString(R.error(5000,"认证已过期")));
        }else {
            log.info("-----------页面跳转 SESSION 过期处理-----------");
            res.sendRedirect("/security/login");
        }
    }

    protected void cancelCookie(HttpServletRequest req, HttpServletResponse res){
        Cookie cookie = new Cookie("JSESSIONID",null);
        cookie.setMaxAge(0);
        cookie.setPath(getCookiePath(req));
        res.addCookie(cookie);
    }

    protected String getCookiePath(HttpServletRequest req){
        String contextPath = req.getContextPath();
        return contextPath.length()>0? contextPath:"/";
    }

}
